<template>
  <div class="container">
    <!-- 背景色块 -->
    <div class="background-shape shape-1"></div>
    <div class="background-shape shape-2"></div>

    <section class="wrapper">
      <header>
        <div class="logo">
          <span>Logo</span>
        </div>
        <h1>{{ isRegister ? "注册账号" : "欢迎登陆" }}</h1>
        <p>{{ isRegister ? "请输入注册信息" : "请登录" }}</p>
      </header>

      <el-form
        :model="form"
        ref="loginForm"
        label-width="0px"
        @keyup.enter="handleLoginOrRegister"
      >
        <transition name="form-fade" mode="out-in">
          <div :key="isRegister ? 'register' : 'login'">
            <el-form-item prop="username" v-if="isRegister">
              <el-input v-model="form.username" placeholder="用户名"></el-input>
            </el-form-item>

            <el-form-item prop="email" v-if="isRegister">
              <el-input v-model="form.email" placeholder="邮箱"></el-input>
            </el-form-item>

            <el-form-item prop="phone">
              <el-input v-model="form.phone" placeholder="手机号码"></el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                type="password"
                v-model="form.password"
                placeholder="密码"
              ></el-input>
            </el-form-item>

            <el-form-item prop="confirmPassword" v-if="isRegister">
              <el-input
                type="password"
                v-model="form.confirmPassword"
                placeholder="确认密码"
              ></el-input>
            </el-form-item>

            <el-form-item v-if="!isRegister" prop="verifyCode">
              <el-row :gutter="10">
                <el-col :span="16">
                  <img
                    @click="!captchaLoading && refreshCaptcha()"
                    :class="{ 'captcha-disabled': captchaLoading }"
                    :src="captchaImage"
                    alt="验证码"
                    style="height: 30px; width: 100%; cursor: pointer"
                  />
                </el-col>
                <el-col :span="8">
                  <el-input
                    style="width: 155px"
                    v-model="form.verifyCode"
                    placeholder="验证码"
                  ></el-input>
                </el-col>
              </el-row>
              <el-button
                type="text"
                class="captcha-refresh"
                @click="refreshCaptcha"
                :disabled="captchaLoading"
                style="margin-top: 60px; margin-left: -286px"
              >
                {{ captchaButtonText }}
              </el-button>
            </el-form-item>
          </div>
        </transition>

        <el-form-item class="login-button">
          <el-button type="primary" @click="handleLoginOrRegister">
            {{ isRegister ? "注册" : "登陆" }}
          </el-button>
        </el-form-item>
      </el-form>

      <footer>
        <p>
          <a href="#" @click.prevent="goToForgotPassword">忘记密码?</a>
        </p>
        <p>
          <a href="#" @click.prevent="toggleMode">
            {{ isRegister ? "已有账号? 登录" : "注册账号" }}
          </a>
        </p>
      </footer>
    </section>
  </div>
</template>

<script setup>
import api from "@/util/service";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useLoginStore } from "@/stores/userStores";

const stores = useLoginStore();
const form = reactive({
  username: "",
  password: "",
  email: "",
  phone: "",
  confirmPassword: "",
  verifyCode: "",
  codeId: "",
});

const captchaImage = ref("");
const captchaButtonText = ref("点击图片刷新");
const captchaLoading = ref(false);
const loginForm = ref(null);
const isRegister = ref(false);
const router = useRouter();

// 获取验证码
const getCaptcha = () => {
  captchaLoading.value = true;
  captchaButtonText.value = "60s后刷新";
  let count = 60;
  const timer = setInterval(() => {
    captchaButtonText.value = `${--count}s后刷新`;
    if (count === 0) {
      clearInterval(timer);
      captchaButtonText.value = "刷新";
      captchaLoading.value = false;
    }
  }, 1000);

  api.post(`/upuser/getCode?t=${new Date().getTime()}`).then((res) => {
    if (res.code === 200) {
      captchaImage.value = res.data.img;
      form.codeId = res.data.codeId;
    }
  });
};
// 刷新验证码
const refreshCaptcha = () => {
  if (!captchaLoading.value) {
    getCaptcha();
  }
};

// 登录或注册处理
const handleLoginOrRegister = async () => {
  if (isRegister.value) {
    // 注册逻辑
    if (form.password !== form.confirmPassword) {
      ElMessage({
        message: "两次输入的密码不一致",
        type: "error",
      });
      return;
    }

    const registerData = {
      username: form.username,
      password: form.password,
      email: form.email,
    };

    api
      .post("/upuser/register", registerData)
      .then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: "注册成功",
            type: "success",
          });
          // 切换到登录模式
          isRegister.value = false;
          // 清空表单
          Object.keys(form).forEach((key) => {
            form[key] = "";
          });
        } else {
          ElMessage({
            message: "注册失败",
            type: "error",
          });
        }
      })
      .catch((error) => {
        ElMessage({
          message: "注册失败",
          type: "error",
        });
      });
  } else {
    // 登录逻辑
    if (form.verifyCode.trim() === "") {
      ElMessage({
        message: "请输入验证码",
        type: "error",
      });
      return;
    }

    const data = {
      verifyCode: form.verifyCode,
      codeId: form.codeId,
      phone: form.phone,
      password: form.password,
    };
    try {
      await stores.login(data).then((res) => {
        if (res.code === 200) {
          // 处理后端返回的数据
          const tokenValue = res.data.token;
          // 更新store中的用户信息和token
          stores.setterUserDetail({
            id: res.data.user.userid,
            username: res.data.user.username,
            imgPath: res.data.user.icon,
            email: res.data.user.email,
            phone: res.data.user.phone,
            utypeid: res.data.user.utypeid,
            menus: res.data.user.menus,
            lid: res.data.user.lid,
            userToken: tokenValue,
          });
          sessionStorage.setItem("token", stores.getToken);
          router.push("/main");
        } else {
          ElMessage({
            message: "登陆失败: " + res.message,
            type: "error",
          });
          refreshCaptcha();
        }
      });
    } catch (error) {
      ElMessage({
        message: "登陆失败: " + error.message,
        type: "error",
      });
      refreshCaptcha();
    }
  }
};

const toggleMode = () => {
  isRegister.value = !isRegister.value;
  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
};

const goToForgotPassword = () => {
  console.log("Go to forgot password");
};

onMounted(() => {
  getCaptcha();
});
</script>
<style src="../../assets/index.scss" scoped></style>
